package com.zoro.barn.business.service.pp.business.project.service;

import com.zoro.barn.business.service.pp.business.project.dao.BarnProjectUserMapper;
import com.zoro.barn.business.service.pp.business.project.entity.BarnProjectUser;
import com.zoro.barn.commons.tools.string.IDs;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhaoxingwu
 */
@Service
public class BarnProjectUserService {

    @Resource
    private BarnProjectUserMapper barnProjectUserMapper;


    /**
     * add users for a project
     *
     * @param projectId project id
     * @param userIds   user ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUsers(String projectId, String[] userIds) {

        if (StringUtils.isBlank(projectId) || userIds == null || userIds.length == 0) {
            return;
        }

        Set<String> ids = new HashSet<>(Arrays.asList(userIds));
        Set<BarnProjectUser> data = ids.stream().filter(id -> barnProjectUserMapper.hasUser(projectId, id) == 0).map(id -> {
            BarnProjectUser bu = new BarnProjectUser();
            bu.setPid(IDs.uuid());
            bu.setProjectId(projectId);
            bu.setUserId(id);
            return bu;
        }).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        this.barnProjectUserMapper.insertBatch(data);
    }

    public List<BarnProjectUser> getUsers(String projectId) {
        BarnProjectUser param = new BarnProjectUser();
        param.setProjectId(projectId);
        return this.barnProjectUserMapper.query(param);
    }

    public void deleteUser(String projectId, String userId) {
        this.barnProjectUserMapper.deleteUser(projectId,userId);
    }
}
